
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QPalette>
#include <QDesktopWidget>
#include <QCloseEvent>
#include <QMenu>
#include <QSystemTrayIcon>
#include <QAction>
#include <QBitmap>
#include <QCloseEvent>
#include <QGraphicsDropShadowEffect>
#include <QMenu>
#include <QPainter>
#include <QSettings>


#include <QItemDelegate>
#include <QMenu>
#include <QMouseEvent>
#include "systemtrayicon.hpp"

class ItemDelegate : public QItemDelegate
{
public:
    ItemDelegate() {}
    ~ItemDelegate() {}
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        QStyleOptionViewItem viewOption(option);
        // 高亮显示与普通显示时的前景色一致（即选中行和为选中时候的文字颜色一样）
        viewOption.palette.setColor(QPalette::HighlightedText, index.data(Qt::ForegroundRole).value<QColor>());
        QItemDelegate::paint(painter, viewOption, index);
    }
};

MyDateTime dt;
CDatabase *g_db;
SystemTrayIcon *sti;
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
                                          ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    g_db = new CDatabase;
    int h = QApplication::desktop()->height();
    this->move(QApplication::desktop()->width() - this->width(),
               h - this->height() - ((h > 1080) ? 48 : 36));

    qDebug() << QApplication::desktop()->width();
    qDebug() << QApplication::desktop()->height();
    SeeThroughWindow(ui->groupBox_ui);

    sti = new SystemTrayIcon(this);


    // 数据库初始化
    g_db->create();

    // 界面样式初始化
    m_dataModel = new QStandardItemModel();

    ui_TableView_Init();
    ui_TableView_Show();

    ui->pushButton_new->setVisible(true);
    ui->pushButton_week->setVisible(true);

    g_h = ui->groupBox_input->height();
    ui->groupBox_input->setFixedHeight(0);
    ui->lineEdit->setFocus();
}

MainWindow::~MainWindow()
{
    delete ui;
}

///////////////////////////////////////////////////////////////////////////


void MainWindow::tableViewShowFrom()
{
    if (!this->isMaximized())
    {
        ui->tableView->horizontalHeader()->setVisible(false); // 隐藏水平表头
        ui->tableView->setColumnHidden(EN_ID, true);          // 隐藏列
        ui->tableView->setColumnHidden(EN_DATE, true);        // 隐藏列
        ui->tableView->setColumnHidden(EN_TIME, true);        // 隐藏列
        ui->tableView->setColumnHidden(EN_STATUS, true);      // 隐藏列
    }
    else
    {
        ui->tableView->horizontalHeader()->setVisible(true); // 隐藏水平表头
        // ui->tableView->setColumnHidden(EN_ID, false);     //隐藏列
        ui->tableView->setColumnHidden(EN_DATE, false);   // 隐藏列
        ui->tableView->setColumnHidden(EN_TIME, false);   // 隐藏列
        ui->tableView->setColumnHidden(EN_STATUS, false); // 隐藏列
    }
}

void MainWindow::mouseDoubleClickEvent(QMouseEvent *e)
{
    if (ui->groupBox_heard->geometry().contains(this->mapFromGlobal(QCursor::pos())))
    {
        if (this->isMaximized())
        {
            this->showNormal();
            m_nocheck = false;
        }
        else
        {
            this->showMaximized();
            m_nocheck = true;
        }
        tableViewShowFrom();
    }
    else
    {
        QMainWindow::mouseDoubleClickEvent(e);
    }
}

///////////////////////////////////////////////////////////////////////////

void MainWindow::SeeThroughWindow(QGroupBox *gui)
{
    this->setWindowOpacity(0.8);
    this->setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);

    QGraphicsDropShadowEffect *ef = new QGraphicsDropShadowEffect;
    ef->setOffset(1, 1);
    ef->setColor(QColor(0, 0, 0, 50));
    ef->setBlurRadius(10);
    gui->setGraphicsEffect(ef);
}

void MainWindow::enterEvent(QEvent *event)
{
    (void)event;
    this->setWindowOpacity(1);
}
void MainWindow::leaveEvent(QEvent *event)
{
    (void)event;
    if (!m_nocheck && !this->isMaximized())
        this->setWindowOpacity(0.8);
}
void MainWindow::mousePressEvent(QMouseEvent *envent)
{
    if (envent->button() == Qt::LeftButton)
    {
        m_mousepressed = true;
        m_pos = envent->globalPos() - this->pos();
    }
}
void MainWindow::mouseReleaseEvent(QMouseEvent *envent)
{
    (void)envent;
    m_mousepressed = false;
}
void MainWindow::mouseMoveEvent(QMouseEvent *envent)
{
    if (m_mousepressed)
    {
        // move(envent->globalPos()-m_pos); //to x,y
        move(this->pos().x(), (envent->globalPos() - m_pos).y()); // only y
    }
}

///////////////////////////////////////////////////////////////////////////

bool MainWindow::deleteData(QString tabname, int id, bool msg)
{
    if (msg)
    {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, " ",
                                      "是否删除这条内容 ？",
                                      QMessageBox::Yes | QMessageBox::No);
        if (reply == QMessageBox::No)
            return true;
    }

    g_db->deleteById(tabname, id);
    ui_TableView_Show();
    return true;
}

// 菜单-删除
void MainWindow::actionDelInfo_triggered()
{
    STU_DATA data;
    ui_TableView_GetData(&data);
    deleteData(data.status == -1 ? "todo" : "done", data.id, true);
}

// 菜单-修改内容
void MainWindow::actionUpdateInfo_triggered()
{
    //    ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked);
    ui_TableView_GetData(&up_data);
    ui->pushButton_done->setText("修改");
    ui->groupBox_input->setFixedHeight(g_h);
    ui->lineEdit->setText(up_data.comm);
    ui->lineEdit->setFocus();
    ui->checkBox->setVisible(false);
}

// 菜单-修改状态
void MainWindow::actionStatus_triggered()
{
    STU_DATA data;
    ui_TableView_GetData(&data);

    if (data.status != -1) //待办
    {
        data.tab = "todo";
        data.date = dt.currentDateValue();
        data.time = dt.currentTimeValue();
        data.status = -1;
        g_db->insert(&data);
        deleteData("done", data.id, false);
    }
    else // 完成
    {
        data.tab = "done";
        data.date = dt.currentDateValue();
        data.time = dt.currentTimeValue();
        data.status = 0;
        g_db->insert(&data);
        deleteData("todo", data.id, false);
    }
}

// 视图点击右键
void MainWindow::slotContextMenu(QPoint pos)
{
    auto index = ui->tableView->indexAt(pos);
    if (index.isValid())
    {
        STU_DATA data;
        ui_TableView_GetData(&data);
        actionStatus->setText((data.status == -1) ? "完  成" : "待  办");
        if (data.status != -1 && data.date != dt.currentDateValue())
            actionStatus->setVisible(false);
        else
            actionStatus->setVisible(true);
        popMenu->exec(QCursor::pos()); // 菜单出现的位置为当前鼠标的位置
    }
}

class CustomTableView
{
    QTableView *tab;
public:
    CustomTableView(QTableView *_tab)
    {
        tab = _tab;

    }
};

// 初始化表
void MainWindow::ui_TableView_Init()
{
    ui->tableView->setItemDelegate(new ItemDelegate); // 选中不改变前景色
    /*样式*/
    ui->tableView->setFocusPolicy(Qt::NoFocus);                          // 设置无虚线
    ui->tableView->verticalHeader()->setVisible(false);                  // 隐藏水平表头
    ui->tableView->verticalHeader()->setDefaultSectionSize(30);          // 设置行高
    ui->tableView->horizontalHeader()->setVisible(false);                // 隐藏垂直表头
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);  // 选择整行
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection); // 只选择一行
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);   // 设置只读
    ui->tableView->setFrameShape(QFrame::NoFrame);                       // 设置无边框
    // ui->tableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); //设置表头居左
    // ui->tableView->setShowGrid(false); //设置不显示格子
    ui->tableView->horizontalHeader()->setStretchLastSection(true); // 最后一列填满表

    /*菜单*/
    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu); // 可弹出右键菜单

    popMenu = new QMenu(ui->tableView);
    actionStatus = new QAction();
    actionUpdateInfo = new QAction();
    actionDelInfo = new QAction();

    popMenu->addAction(actionStatus);
    popMenu->addAction(actionUpdateInfo);
    popMenu->addAction(actionDelInfo);

    connect(actionStatus, SIGNAL(triggered()), this, SLOT(actionStatus_triggered()));
    connect(actionDelInfo, SIGNAL(triggered()), this, SLOT(actionDelInfo_triggered()));
    connect(actionUpdateInfo, SIGNAL(triggered()), this, SLOT(actionUpdateInfo_triggered()));

    actionUpdateInfo->setText(QString("修  改"));
    actionDelInfo->setText(QString("删  除"));
    connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotContextMenu(QPoint)));
}

QColor tocolor(int date)
{
    int day = dt.tostart("Today");
    int tw = dt.tostart("Week");
    int lw = dt.tostart("7Day");
    int m = dt.tostart("Month");

    if (date >= day)
    {
        return QColor(10, 10, 10);
    }
    else if (date >= tw)
    {
        return QColor(50, 50, 50);
    }
    else if (date >= lw)
    {
        return QColor(100, 100, 100);
    }
    else if (date >= m)
    {
        return QColor(150, 150, 150);
    }
    else
    {
        return QColor(200, 200, 200);
    }
}


QString tonextflg(QString flg)
{
    QStringList arr = {"Today", "Week", "7Day", "Month", "All"};
    for (int i = 0; i < arr.length() - 1; i++)
    {
        if (flg == arr.at(i))
            return arr.at(i + 1);
    }
    return arr.at(0);
}

// 显示数据库
bool MainWindow::ui_TableView_Show()
{
    ui->pushButton->setText("All");
    on_pushButton_clicked();
    return true;
}

// 获得选中用户信息
void MainWindow::ui_TableView_GetData(STU_DATA *data)
{
    QModelIndex c = ui->tableView->currentIndex();
    QAbstractItemModel *Imodel = ui->tableView->model();
    data->id = Imodel->data(Imodel->index(c.row(), EN_ID)).toInt();
    data->date = Imodel->data(Imodel->index(c.row(), EN_DATE)).toInt();
    data->time = Imodel->data(Imodel->index(c.row(), EN_TIME)).toInt();
    //    data->status = Imodel->data(Imodel->index(c.row(), EN_STATUS)).toInt();
    data->status = Imodel->data(Imodel->index(c.row(), EN_STATUS)).toString() == "完成" ? 0 : -1;
    data->comm = Imodel->data(Imodel->index(c.row(), EN_COMM)).toString();
}
void MainWindow::tabchange(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
{
    QString newstr = topLeft.data().toString();
    if (newstr == "")
    {
        return;
    }
    if (newstr != up_data.comm)
    {
        qDebug() << topLeft.data().toString();
        up_data.comm = newstr;
        g_db->updateById(&up_data);
    }
}

void MainWindow::on_pushButton_clicked()
{
    QString flg = ui->pushButton->text();
    qDebug() << "=====================";
    qDebug() << tonextflg(flg);
    ui->pushButton->setText(tonextflg(flg));
    flg = ui->pushButton->text();

    // 清除以前new的itemId
    QStandardItemModel *model = m_dataModel;
    model->clear();
    //    disconnect(m_dataModel, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &, const QVector<int> &)),
    //            this, SLOT(tabchange(const QModelIndex &, const QModelIndex &, const QVector<int> &)));

    QStandardItem *itemId;
    QStandardItem *itemDate;
    QStandardItem *itemTime;
    QStandardItem *itemStatus;
    QStandardItem *itemComm;

    QString cmd;

    int i = 0;
    QSqlQuery query;

    cmd = QString("SELECT * FROM todo order by id desc");
    qDebug() << cmd;
    query.exec(cmd);
    while (query.next())
    {
        // 标准项, 用来保存一个数据项
        itemId = new QStandardItem;
        itemDate = new QStandardItem;
        itemTime = new QStandardItem;
        itemStatus = new QStandardItem;
        itemComm = new QStandardItem;

        itemId->setData(mQueryI(query, EN_ID), 0);
        itemDate->setData(mQueryI(query, EN_DATE), 0);
        itemTime->setData(mQueryI(query, EN_TIME), 0);
        //        itemStatus->setData(mQueryI(query, EN_STATUS), 0);
        itemStatus->setData("待办", 0);
        itemComm->setData(mQueryS(query, EN_COMM), 0);

        // 添加设置数据
        model->setItem(i, EN_ID, itemId);
        model->setItem(i, EN_DATE, itemDate);
        model->setItem(i, EN_TIME, itemTime);
        model->setItem(i, EN_STATUS, itemStatus);
        model->setItem(i, EN_COMM, itemComm);
        model->item(i, EN_COMM)->setForeground(QBrush(QColor(0, 110, 32)));
        //        model->item(i, EN_COMM)->setBackground(QBrush(QColor(240,255,240)));

        i++;
    }

    cmd = QString("SELECT * FROM done WHERE date>=%1 order by id desc")
              .arg(dt.tostart(flg));
    qDebug() << cmd;

    query.exec(cmd);
    while (query.next())
    {
        //        qDebug() << query.value(EN_ID).toInt()
        //                 << query.value(EN_DATE).toInt()
        //                 << query.value(EN_TIME).toInt()
        //                 << query.value(EN_STATUS).toInt()
        //                 << query.value(EN_COMM).toString();

        // 标准项, 用来保存一个数据项
        itemId = new QStandardItem;
        itemDate = new QStandardItem;
        itemTime = new QStandardItem;
        itemStatus = new QStandardItem;
        itemComm = new QStandardItem;

        itemId->setData(mQueryI(query, EN_ID), 0);
        itemDate->setData(mQueryI(query, EN_DATE), 0);
        itemTime->setData(mQueryI(query, EN_TIME), 0);
        //        itemStatus->setData(mQueryI(query, EN_STATUS), 0);
        itemStatus->setData("完成", 0);
        itemComm->setData(mQueryS(query, EN_COMM), 0);

        // 添加设置数据
        model->setItem(i, EN_ID, itemId);
        model->setItem(i, EN_DATE, itemDate);
        model->setItem(i, EN_TIME, itemTime);
        model->setItem(i, EN_STATUS, itemStatus);
        model->setItem(i, EN_COMM, itemComm);

        model->item(i, EN_COMM)->setForeground(QBrush(tocolor(mQueryI(query, EN_DATE))));

        i++;
    }

    model->setColumnCount(EN_MAX);
    model->setHeaderData(EN_ID, Qt::Horizontal, "编号");
    model->setHeaderData(EN_DATE, Qt::Horizontal, "日期");
    model->setHeaderData(EN_TIME, Qt::Horizontal, "时间");
    model->setHeaderData(EN_STATUS, Qt::Horizontal, "状态");
    model->setHeaderData(EN_COMM, Qt::Horizontal, "内容");

    ui->tableView->setModel(model); // 设置模型

    //    connect(m_dataModel, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &, const QVector<int> &)),
    //            this, SLOT(tabchange(const QModelIndex &, const QModelIndex &, const QVector<int> &)));

    tableViewShowFrom();

    return;
}

void MainWindow::on_pushButton_new_clicked()
{
    if (ui->groupBox_input->height() == 0)
    {
        ui->lineEdit->clear();
        ui->lineEdit->setFocus();
        ui->pushButton_done->setText("添加");
        ui->checkBox->setChecked(true);
        ui->checkBox->setVisible(true);
        ui->lineEdit->setPlaceholderText("今日完成  ");
        ui->groupBox_input->setFixedHeight(g_h);
    }
    else
    {
        ui->lineEdit->clear();
        ui->groupBox_input->setFixedHeight(0);
    }
}

void MainWindow::on_pushButton_week_clicked()
{
    int start, stop;
    dt.weekStartStop(&start, &stop);

    QStringList list;

    g_db->read(start, stop, list);

    if (list.length() == 0)
        return;

    if (m_lb == nullptr)
    {
        m_lb = new QTextEdit();
    }

    m_lb->clear();
    for (int i = 0; i < list.length(); i++)
    {
        m_lb->append(QString::number(i + 1) + ". " + list.at(i));
    }
    m_lb->setStyleSheet("color:#7a8a8c;background:#2e2f30;"
                        "margin:10px 20px;font-size:12pt;"
                        "selection-background-color:#55555a;");
    m_lb->resize(600, 280);
    m_lb->setWindowTitle("本周内容");
    m_lb->setWindowIcon(QIcon(":/img/logo.ico"));
    m_lb->show();
}

void MainWindow::on_pushButton_done_clicked()
{
    ui->checkBox->setVisible(false);
    if (ui->lineEdit->text().length() == 0)
    {
        ui->groupBox_input->setFixedHeight(0);
        return;
    }

    if (ui->pushButton_done->text() == "添加")
    {
        STU_DATA data;
        data.tab = (ui->checkBox->isChecked()) ? "done" : "todo";
        data.status = (ui->checkBox->isChecked()) ? 0 : -1;
        data.date = dt.currentDateValue();
        data.time = dt.currentTimeValue();
        data.comm = ui->lineEdit->text();

        g_db->insert(&data);
        ui_TableView_Show();
    }
    else if (ui->pushButton_done->text() == "修改")
    {
        if (ui->lineEdit->text() == up_data.comm)
        {
            ui->lineEdit->clear();
            ui->groupBox_input->setFixedHeight(0);
            return;
        }
        up_data.comm = ui->lineEdit->text();
        g_db->updateById(&up_data);
        ui_TableView_Show();
    }
    ui->lineEdit->clear();
    ui->groupBox_input->setFixedHeight(0);
}

void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    if (ui->groupBox_input->height() == 0)
    {
        qDebug() << "input!! " << arg1;
        ui->lineEdit->clear();
    }
}

void MainWindow::on_lineEdit_editingFinished()
{
    if (!ui->checkBox->hasFocus())
        on_pushButton_done_clicked();
}

void MainWindow::on_tableView_doubleClicked(const QModelIndex &index)
{
    // ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);     //设置只读
    (void)index;
    m_nocheck = true;
    //    qDebug()<<ui->tableView->pos();
    //    qDebug()<<ui->tableView->mapFromGlobal(this->cursor().pos());
    slotContextMenu(ui->tableView->mapFromGlobal(this->cursor().pos()));
    m_nocheck = false;
}

void MainWindow::on_tableView_clicked(const QModelIndex &index)
{
    (void)index;
    if (ui->groupBox_input->height() != 0)
    {
        ui->lineEdit->clear();
        ui->groupBox_input->setFixedHeight(0);
    }
}

void MainWindow::on_checkBox_clicked(bool checked)
{
    QString str = (checked) ? "今日完成  " : "计划任务  ";
    ui->lineEdit->setPlaceholderText(str);
}
